
propsage.namespace("prestige.commissionPayable");

prestige.commissionPayable.create = (function($, ui) {

	function initComponents() {

		if($('#PayableItem_id').val()){
			$('#btnSelPayableItem').addClass('disabled');
		}
		
		$("#choosePayableItemDlg tr:odd").addClass("odd");
		$("#choosePayableItemDlg").dialog({
			'width': 900,
			'autoOpen': false,
			'resizable': false,
			'modal': true,
			'buttons': {
				'Cancel': onDialogCancel,
				'OK': {
					'text': 'OK',
					'class': 'blue',
					'click': onChoosePayableItemOK
				}
			},
			'open': onChoosePayableItemOpen
		});
		$("#choosePartyDlg").dialog({
			'width': 900,
			'autoOpen': false,
			'resizable': false,
			'modal': true,
			'buttons': {
				'Cancel': onDialogCancel
			},
			'open': onChoosePartyOpen
		});
		$("#chooseTransactionDlg").dialog({
			'width': 900,
			'autoOpen': false,
			'resizable': false,
			'modal': true,
			'buttons': {
				'Cancel': onDialogCancel,
				'OK': {
					'text': 'OK',
					'class': 'blue',
					'id': 'transOK',
					'click': onChooseTransactionOK
				}
			},
			'open': onChooseTransactionOpen
		});
		$("#chooseReceiptDlg").dialog({
			'width': 900,
			'autoOpen': false,
			'resizable': false,
			'modal': true,
			'buttons': {
				'Cancel': onDialogCancel,
				'OK': {
					'text': 'OK',
					'class': 'blue',
					'click': onChooseReceiptOK
				}
			},
			'open': onChooseReceiptOpen
		});

		$('#btnChooseParty').PsSearchBillableParty({
			'clearButton': '#btnClearAgent',
			'fields': {
				'party_id': '#PayableItem_payee_party_id',
				'actualname': '#PayableItem_payee_name'
			}
		});

		if ($('#PayableItem_property_case_id').val() !== "0") {
			var transId = $('#PayableItem_property_case_id').val();
			$('#select-transaction-grid input:radio[value="' + transId + '"]').prop('checked', true);
			$('#transOK').trigger('click');
		}
	}

	function initEventHandlers() {
		$('#btnSelPayableItem').click(onBtnSelPayableItemClick);
		$('#btnSelPayee').click(onBtnSelPayeeClick);
		$('#btnSelTransaction').click(onBtnSelTransactionClick);
		$('#btnSelReceipt').click(onBtnSelReceiptClick);
		$('#PayableItem_comm_type').change(onPayableItemCommTypeChange);
		$('#PayableItem_net_amount').change(onAdjustmentNetAmountChange);
		$('#PayableItem_net_amount_total').change(onAdjustmentTotalNetAmountChange);
		$('#choosePayableItemDlg table').delegate('tr', 'click', onRowSelected);
		$('#chooseReceiptDlg table').delegate('tr', 'click', onRowSelected);
		$('#chooseTransactionDlg table').delegate('tr', 'click', onRowSelected);
		$('#btnFinish, #btnNext').click(onBtnSubmitClick);
		$('#PayableItem_payee_party_id').change(onPayeePartyIdChange);
		$('#agency_payee_chkbox').click(onAgencyPayeeChkBoxClicked);
	}

	function onAgencyPayeeChkBoxClicked()
	{
		if ($(this).attr("checked") == "checked") {
			$('#PayableItem_comm_type option').attr('disabled', false);
			$('#PayableItem_comm_type').val('agency');
			$('#PayableItem_comm_type').trigger('change');
			$('tr.selectable').hide();
		} else {
			$('#PayableItem_comm_type').attr('disabled', true);
			$('#PayableItem_comm_type').val('');
			$('#PayableItem_payee_party_id').val('');
			$('#PayableItem_payee_name').val('');
			$('tr.selectable').show();

		}
	}

	function onPayeePartyIdChange() {
		var partyId = $(this).val();
		if (partyId == $('#agencyPartyId').val()) {
			$('#PayableItem_comm_type').val('agency');
			$('#PayableItem_comm_type').attr('disabled', true);
		} else {
			ui.doAjax('GET', baseUrl + '/commissionPayable/ajaxGetCommType/' + partyId, {
				}, onCommTypeFoundSuccess);
		}
	}

	function onCommTypeFoundSuccess(response) {
		if (response.result == 'success') {
			var $commTypeOptions = $('#PayableItem_comm_type option');
			var $commTypeOptionsSelectable = $commTypeOptions.filter(function() {
				return $(this).text() != "External" && $(this).text() != "Company";
			});
			var $commTypeOptionsNotSelecteable = $commTypeOptions.filter(function() {
				return $(this).text() == "External" || $(this).text() == "Company";
			});

			if (response.is_external) {
				$commTypeOptionsSelectable.attr('disabled', 'disabled');
				$commTypeOptionsNotSelecteable.attr('disabled', false);
				$('#PayableItem_comm_type').val('external');
				$('#PayableItem_comm_type').attr('disabled', true);
			} else {
				$commTypeOptionsSelectable.attr('disabled', false);
				$commTypeOptionsNotSelecteable.attr('disabled', 'disabled');
				$('#PayableItem_comm_type').val('');
				$('#PayableItem_comm_type').attr('disabled', false);
			}
		}
	}

	function onBtnSubmitClick(e)
	{
		if ($(this).hasClass('disabled')) {
			e.preventDefault();
		} else {
			if (!$('#PayableItem_description').val()) {
				alert('Description cannot be blank');
				$('#PayableItem_description').focus();
				return false;
			}
			if (!$('#PayableItem_comm_type').val()) {
				alert('Please select Commission Type for ' + $('#PayableItem_payee_name').val());
				$('#PayableItem_comm_type').focus();
				return false;
			}
		}
		$('#PayableItem_comm_type').attr('disabled', false);
		var submitValue = $('#PayableItem_net_amount').autoNumeric('get');
		$('#PayableItem_net_amount').val(submitValue);
	}

	function onPayableItemCommTypeChange()
	{

		if ($('#PayableItem_comm_type').val() == 'agency') {
			var name = $('#agencyName').val();
			var partyId = $('#agencyPartyId').val();
			$('#PayableItem_payee_name').val(name);
			$('#PayableItem_payee_party_id').val(partyId);
		}
	}

	function onDialogCancel()
	{
		$(this).dialog('close');
	}

	function onChoosePayableItemOK()
	{
		var selectedData = $(this).find('input[type="radio"]:checked');

		if (selectedData.length === 0) {
			alert("Please select a payable item");
			return false;
		}

		var payableItemId = $(this).find('input[type="radio"]:checked').val();
		$('#PayableItem_id').val(payableItemId);

		var commType = $(this).find('input[type="radio"]:checked').closest('tr').find('td.comm-type-column').text();
		$('#PayableItem_comm_type').val(commType);

		if (selectedData.length === 1) {
			var $row = $(this).find('input[type="radio"]:checked').closest('tr');
			$row.find('td').each(function() {
				var $inputs = $(this).find('input');
				if ($inputs) {
					$inputs.each(function() {
						//						console.log($(this).attr('id'));
						$('#' + $(this).attr('id')).val($(this).val());
					});

				}
			});
		}

		if (commType != 'Company') {
			var propertyCaseId = $('#PayableItem_property_case_id').val();
			ui.doAjax('GET', baseUrl + '/commissionPayable/ajaxCheckAgencyPayableItemExists/' + propertyCaseId, {
				}, onCheckAgencyPayableItemSuccess);
		} else {
			$('#auto-agency-row').hide();
		}

		$('#choosePayableItemDlg').dialog('close');

	}

	function onCheckAgencyPayableItemSuccess(response)
	{
		if (response.result == 'success') {
			$('#auto-agency-row').toggle(response.agencyPayeeExists);
		}
	}


	function onChoosePayableItemOpen(event) {

	}

	function onBtnSelPayableItemClick(e) 
	{
		if ($(this).hasClass('disabled')) {
			e.preventDefault();
		} else {
			$('#choosePayableItemDlg').dialog('open');
		}
	}

	function onBtnSelPayeeClick() {
		$('#choosePartyDlg').dialog('open');
	}

	function onBtnSelTransactionClick() {
		$('#chooseTransactionDlg').dialog('open');
	}

	function onBtnSelReceiptClick() {
		$('#chooseReceiptDlg').dialog('open');
	}

	function onAdjustmentTotalNetAmountChange(event) {
		var adjustment_amount = $('#PayableItem_net_amount_before').val();
		var total_net_amount = $(this).autoNumeric('get');
		var net_amount = 0;

		if (isNaN(total_net_amount)) {
			adjustment_amount = 0.00;
		}

		net_amount = total_net_amount - adjustment_amount;

		$('#PayableItem_net_amount').autoNumeric('set', net_amount.toFixed(2));
	}

	function onAdjustmentNetAmountChange(event) {

		if ($('#type').val() == 'adjustment') {		//check if current page is for adjustment 
			var adjustment_amount = parseFloat($('#PayableItem_net_amount').autoNumeric('get'));
			var net_amount = parseFloat($('#PayableItem_net_amount_before').val());
			var total_net_amount = 0;

			if (isNaN(adjustment_amount)) {
				adjustment_amount = 0.00;
			}

			total_net_amount = net_amount + adjustment_amount;

			$('#PayableItem_net_amount_total').autoNumeric('set', total_net_amount.toFixed(2));
		}
	}

	function onPartySelected(event, ui) {

	}

	function onChoosePartyOpen() {

	}

	function onChooseTransactionOpen() {

	}

	function onChooseTransactionOK() {
		var selectedData = $(this).find('input[type="radio"]:checked');
		if (selectedData.length === 0) {
			alert("Please select a transaction");
			return false;
		}

		var propertyCaseId = $(this).find('input[type="radio"]:checked').val();
		$('#PayableItem_property_case_id').val(propertyCaseId);

		var address = $(this).find('input[type="radio"]:checked').closest('tr').find('td.trans-prop').text();

		var caseNumber = $('#select-transaction-grid').find('input[type="radio"]:checked').closest('tr').find('td.trans-no').text();
		$('#PayableItem_case_number').val(caseNumber);

		$('#agents table').remove();
		$('#items table').remove();

		$('#addPayableItem .block h3').remove();
		if (address) {
			$('<h3>For the transaction at ' + address + '</h3>').insertAfter('#addPayableItem .block h2');
		}

		ui.doAjax('POST', baseUrl + '/commissionPayable/ajaxGetPropertyCasePayableItems/' + propertyCaseId, {
			}, onPropertyCasePayableItemsLoadSuccess);

		$('table.form-table tr').not('#agency_payee_row').show();
		$('#btnFinish, #btnNext').removeClass('disabled');

		$('#chooseTransactionDlg').dialog('close');
	}

	function onPropertyCasePayableItemsLoadSuccess(response) {
		if (response.result == 'success') {
			var propertyCaseAgents = response.agents;
			var agentCount = response.agentCount;
			var totalGross = response.comm_dollar_value;
			var gstPayable = response.comm_gst_payable;
			var gstStatus = ' not included';
			var gstMsg = '';

			if (gstPayable) {
				if (response.comm_gst_inclusive == 1) {
					gstStatus = ' included'
				}
				;
				gstMsg = 'GST' + gstStatus;
			}

			$('<h3>Total Gross Commission: $' + totalGross + ' ' + gstMsg + '</h3>').insertAfter('#addPayableItem .block h3');

			var $table = $('<table><caption style="text-align:left;margin-bottom:5px;"><strong>Co-broke Information</strong></caption></table>');
			$table.addClass('detailTable');
			$header = $('<tr><td>Salesperson</td><td>Role</td><td style="width:40px;">Gross Commission w GST</td><td style="width:40px;">Gross Commission w/o GST</td></tr>');
			$table.append($header);
			if (agentCount > 0) {
				$.each(propertyCaseAgents, function(i, v) {
					var $row = $('<tr></tr>');
					var string = '<td>' + v['name'] + '</td><td>' + v['role'] + '</td><td style="text-align:right;width:30px;">$' + v['gross'] + '</td><td style="text-align:right;width:30px;">$' + v['earn'] + '</td>';
					$row.append(string);
					$table.append($row);
				});
			} else {
				$table.append('<tr><td colspan="4">No co-brokers found</td></tr>');
			}
			$table.append('<tr><td colspan="2" style="text-align:right;"><strong>Total</strong></td><td style="text-align:right;width:40px;"><strong>$' + response.grossTotal + '</strong</td><td style="text-align:right;width:40px;"><strong>$' + response.earnTotal + '</strong</td></tr>');
			$table.find("tr:even").addClass("alt-row");
			$table.appendTo('#agents');

			var items = response.items;
			var itemCount = response.itemCount;
			var $table = $('<table><caption style="text-align:left;margin-bottom:5px;"><strong>Payable Amounts Allocated</strong></table>');
			$table.addClass('detailTable');
			$header = $('<tr><td>Recipient Name</td><td style="width:30px;">Payable Type</td><td style="width:100px;">Description</td><td style="width:20px;">Payable Amount</td></tr>');
			$table.append($header);
			var hasCompanyPayee = false;
			if (itemCount > 0) {
				$.each(items, function(i, v) {
					if (v['type'] == 'Company')
						hasCompanyPayee = true;
					var $row = $('<tr></tr>');
					var string = '<td>' + v['name'] + '</td><td style="width:30px;">' + v['type'] + '</td><td style="width:100px;">' + v['description'] + '</td><td style="text-align:right;width:20px;">$' + v['amount'] + '</td>';
					$row.append(string);
					$table.append($row);
				});
			} else {
				$table.append('<tr><td colspan="4">No payable items created yet</td></tr>');
			}
			$table.append('<tr><td colspan="3" style="text-align:right;"><strong>Total</strong></td><td style="text-align:right;width:40px;"><strong>$' + response.payableItemsTotal + '</strong</td></tr>');
			$table.find("tr:even").addClass("alt-row");
			$table.appendTo('#items');

		//			$('#agency_payee_row').toggle(!hasCompanyPayee);
		}
	}

	function setSelectedTransaction(propCaseId) {
		selectedTrans.push(propCaseId);
		$('#chooseTransactionDlg input:radio[value="' + propCaseId + '"]').attr('disabled', true).closest('tr').addClass('trans-selected');
	}

	function onChooseReceiptOpen() {

	}

	function onChooseReceiptOK() {
		var receiptId = $(this).find('input[type="radio"]:checked').val();
		$('#PayableItem_payment_id').val(receiptId);

		var paymentNumber = $('#receipt-index-grid').find('input[type="radio"]:checked').closest('tr').find('td.payment_number').text();
		$('#PayableItem_receipt_number').val(paymentNumber);

		$('#chooseReceiptDlg').dialog('close');
	}

	function onRowSelected(event) {
		$(this).find('td input[type="radio"]').prop('checked', true);
	}


	$(document).ready(function() {
		initComponents();
		initEventHandlers();
	});

	return {
		onPartySelected: onPartySelected
	}

}(jQuery, propsage.ui));